package com.sright.bcard.component.biz.manager.impl;

import com.sright.bcard.common.service.share.dto.component.ComponentCufaceMaterialConfigComponentDTO;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import com.sright.bcard.component.biz.manager.ComponentCufaceMaterialConfigComponentManager;
import com.sright.bcard.component.dal.entity.ComponentCufaceMaterialConfigComponentDO;
import com.sright.bcard.content.dal.dao.CardBaseInfoDAO;
import com.sright.bcard.content.dal.dao.CardDAO;
import com.sright.bcard.component.dal.dao.ComponentCufaceMaterialConfigComponentDAO;
import com.sright.bcard.content.dal.entity.CardBaseInfoDO;
import com.sright.bcard.content.dal.entity.CardDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Slf4j
public class ComponentCufaceMaterialConfigComponentManagerImpl implements ComponentCufaceMaterialConfigComponentManager {

    @Autowired
    private CardDAO cardDAO;

    @Autowired
    private CardBaseInfoDAO cardBaseInfoDAO;

    @Autowired
    private ComponentCufaceMaterialConfigComponentDAO componentCufaceMaterialConfigComponentDAO;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Long addOrModify(ComponentCufaceMaterialConfigComponentDTO componentCufaceMaterialConfigComponentDTO) {
        // 构建素材组件实体
        ComponentCufaceMaterialConfigComponentDO componentDO = new ComponentCufaceMaterialConfigComponentDO();
        DataConvertUtils.convertDTO2DO(componentCufaceMaterialConfigComponentDTO, componentDO);
        Long result = componentCufaceMaterialConfigComponentDAO.insertSelective(componentDO);
        // 更新cardBaseInfo的组件ids字段
        CardDO cardDO = cardDAO.selectById(componentCufaceMaterialConfigComponentDTO.getCardId());
        if(null != cardDO) {
            CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectById(cardDO.getBaseInfoId());
            if(null != cardBaseInfoDO) {
                Long componentId = cardBaseInfoDO.getComponentId();
                if(null != componentId || 0 != componentId) {
                    cardBaseInfoDO.setComponentId(result);
                }
            }
            cardBaseInfoDAO.updateSelective(cardBaseInfoDO);
        }
        return result;
    }
}
